import { type BrowserWindow, ipcMain } from "electron";
import type { WindowStateChangeArgs } from "@common/window-ipc";

/// 窗口缓存
const winds = new Map<number, BrowserWindow>();

ipcMain.on("window:minimize", event => winds.get(event.sender.id)?.minimize());
ipcMain.on("window:maximize", event => winds.get(event.sender.id)?.maximize());
ipcMain.on("window:unmaximize", event => winds.get(event.sender.id)?.unmaximize());
ipcMain.on("window:close", event => winds.get(event.sender.id)?.close());

ipcMain.handle("window:get-state", event => {
  const wind = winds.get(event.sender.id);
  return getWindowState(wind);
});

export function registerWindowIpcService(wind: BrowserWindow) {
  winds.set(wind.webContents.id, wind);
  const onWindowStateChanged = getOnWindowStateChanged(wind);
  wind.on("minimize", onWindowStateChanged);
  wind.on("maximize", onWindowStateChanged);
  wind.on("unmaximize", onWindowStateChanged);
  wind.once("close", () => {
    winds.delete(wind.webContents.id);
    wind.off("minimize", onWindowStateChanged);
    wind.off("maximize", onWindowStateChanged);
    wind.off("unmaximize", onWindowStateChanged);
  });
}

function getOnWindowStateChanged(wind: BrowserWindow) {
  return () => {
    wind.webContents.send("window:state-changed", getWindowState(wind));
  };
}

function getWindowState(wind: BrowserWindow | undefined): WindowStateChangeArgs {
  return {
    maximized: wind?.isMaximized() ?? false,
  };
}
